<?php
// ========================== 文件说明 ==========================//
// 本文件说明：模板管理
// --------------------------------------------------------------//
// 本程序作者：angel
// --------------------------------------------------------------//
// 本程序版本：SaBlog-X Ver 1.6
// --------------------------------------------------------------//
// 本程序主页：http://www.sablog.net
// ========================== 开发环境 ==========================//
// register_globals = Off
// --------------------------------------------------------------//
// magic_quotes_gpc = On
// --------------------------------------------------------------//
// safe_mode = On
// --------------------------------------------------------------//
// Windows server 2003 & Linux & FreeBSD
// --------------------------------------------------------------//
// Apache/1.3.33 & PHP/4.3.2 & MySQL/4.0.17
// --------------------------------------------------------------//
// Apache/1.3.34 & PHP/4.4.1 & MySQL/5.0.16
// --------------------------------------------------------------//
// Apache/2.0.55 & PHP/5.1.1 & MySQL/5.0.15
// --------------------------------------------------------------//
// Copyright (C) Security Angel Team All Rights Reserved.
// ==============================================================//

if(!defined('SABLOG_ROOT') || !isset($php_self) || !preg_match("/[\/\\\\]cp\.php$/", $php_self)) {
	exit('Access Denied');
}

//权限检查
permission();

!$action && $action = 'template';

if (in_array($action, array('savefile','donewtemplate','mod','filelist','newtemplate')) && !$tpledit) {
	redirect('不允许在后台修改模板', 'cp.php?job=template');
}

//读取模板套系(目录)
$template_dir = 'templates/';
$path = $_GET['path'] ? $_GET['path'] : $_POST['path'];
$file = $_GET['file'] ? $_GET['file'] : $_POST['file'];
$ext = $_GET['ext'] ? $_GET['ext'] : $_POST['ext'];

$opened = @opendir(SABLOG_ROOT.$template_dir);
$dirdb = array();
while($dir = @readdir($opened)){
	if(($dir != '.') && ($dir != '..') && $dir != 'admin') {
		if (@is_dir($template_dir.$dir)){
			$dirdb[] = $dir;
		}
	}
}
asort($dirdb);
unset($dir);
@closedir($opened);

$path = in_array($path, $dirdb) ? $path : 'default';
if (strstr($file,'.') || strstr($path,'.')) {
	redirect('模板无效', 'cp.php?job=template&action=filelist');
}

//获取模板信息
function get_template_info($infofile) {
	global $template_dir;
	$infofile = str_replace(array('..',':/'),array('',''),$infofile);
	$template_info = @file(SABLOG_ROOT.$template_dir.$infofile);
	if ($template_info) {
		$cssdata = array();
		foreach ($template_info AS $data) {
			$data = str_replace('://','=//',$data);
			$info = explode(':', $data);
			$info[1] = trim(str_replace('=//','://',$info[1]));
			$cssdata[] = $info[1];
		}
		//判断制作者是否有网站
		if ($cssdata[4]) {
			$cssdata[3] = '<a href="'.trim($cssdata[4]).'" title="访问模板作者的网站" target="_blank">'.trim($cssdata[3]).'</a>';
		}
		//判断缩略图是否存在
		$templatedir = dirname($template_dir.$infofile);
		foreach ( array('png', 'gif', 'jpg', 'jpeg') as $ext ) {
			if (file_exists($templatedir.'/screenshot.'.$ext)) {
				$screenshot = $templatedir.'/screenshot.'.$ext;
			}
		}
		$info = array(
			'name' => $cssdata[0],
			'dirurl' => urlencode(dirname($infofile)),
			'version' => $cssdata[1],
			'description' => $cssdata[2],
			'author' => $cssdata[3],
			'screenshot' => $screenshot
		);
		return $info;
	} else {
		return false;
	}
}

//设置模板
if($action == 'settemplate') {
	$name = $_GET['name'];
	if (file_exists(SABLOG_ROOT.$template_dir.$name) && strpos($name,'..')===false) {
		buildtemplate($name);
		$DB->query("REPLACE INTO {$db_prefix}settings VALUES ('templatename', '".sax_addslashes($name)."')");
		settings_recache();
		redirect('模板已经更新', 'cp.php?job=template&action=template');
	} else {
		redirect('模板不存在', 'cp.php?job=template&action=template');
	}
}

//保存文件
if($action == 'savefile' && $tpledit){
	$ext = in_array($ext,array('php','css')) ? $ext : 'php';
	$filepath = SABLOG_ROOT.$template_dir.$path.'/'.$file.'.'.$ext;

	if (file_exists($filepath)) {
		$content = sax_stripslashes(trim($_POST['content']));
		writefile($filepath, $content);
		redirect('模板修改成功', 'cp.php?job=template&action=filelist&path='.$path.'&file='.$file.'&ext='.$ext);
	} else {
		redirect('模板文件不存在', 'cp.php?job=template&action=filelist&path='.$path);
	}
}

//批量处理自定义模板变量
if($action == 'domorestylevar'){
	if($ids = implode_ids($_POST['delete'])) {
		$DB->query("DELETE FROM	{$db_prefix}stylevars WHERE stylevarid IN ($ids)");
	}
	if(is_array($_POST['stylevar'])) {
		foreach($_POST['stylevar'] as $stylevarid => $value) {
			$DB->unbuffered_query("UPDATE {$db_prefix}stylevars SET value='".sax_addslashes(trim($_POST['stylevar'][$stylevarid]))."', visible='".intval($_POST['visible'][$stylevarid])."' WHERE stylevarid='".intval($stylevarid)."'");
		}
	}

	$new_title = strtolower(sax_addslashes($_POST['new_title']));
	$new_value = sax_addslashes($_POST['new_value']);
	if($new_title != '') {
		$query = $DB->query("SELECT COUNT(*) FROM {$db_prefix}stylevars WHERE title='$new_title'");
		if($DB->result($query, 0)) {
			redirect('变量名已经存在,请返回修改');
		} elseif(!preg_match("/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/", $new_title)) {
			redirect('变量名称不合法,请返回修改');
		}
		$DB->query("INSERT INTO {$db_prefix}stylevars (title, value) VALUES ('$new_title', '$new_value')");
	}

	stylevars_recache();
    redirect('自定义模板变量已成功更新', 'cp.php?job=template&action=stylevar');
}

//自定义模板变量
if($action == 'stylevar'){
	if($page) {
		$start_limit = ($page - 1) * 30;
	} else {
		$start_limit = 0;
		$page = 1;
	}
	$total = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}stylevars"), 0);
	$multipage = multi($total, 30, $page, 'cp.php?job=template&action=stylevar');

    $query = $DB->query("SELECT * FROM {$db_prefix}stylevars ORDER BY stylevarid DESC LIMIT $start_limit, 30");

	$stylevardb = array();
	while ($stylevar = $DB->fetch_array($query)) {
		$stylevar['visible_check'] = $stylevar['visible'] ? 'checked' : '';
		$stylevardb[] = $stylevar;
	}
	unset($stylevar);
	$DB->free_result($query);
	$subnav = '自定义模板变量管理';
}

//选择模板
if($action == 'template') {
	$current_infofile = $options['templatename'].'/info.txt';
	if (file_exists(SABLOG_ROOT.$template_dir.$current_infofile)) {
		$current_template_info = get_template_info($current_infofile);
	} else {
		$current_template_info = '';
	}
	foreach ( array('png', 'gif', 'jpg', 'jpeg') as $ext ) {
		if (file_exists(SABLOG_ROOT.$template_dir.$options['templatename'].'/screenshot.'.$ext)) {
			$current_template_info['screenshot'] = $template_dir.$options['templatename'].'/screenshot.'.$ext;
		}
	}

	$dir1 = opendir(SABLOG_ROOT.$template_dir);
	$available_template_db = array();
	while($file1 = readdir($dir1)){
		if ($file1 != '' && $file1 != '.' && $file1 != '..' && $file1 != 'admin' && $file1 != $options['templatename']){
			if (is_dir($template_dir.'/'.$file1)){
				$dir2 = opendir($template_dir.'/'.$file1);
				while($file2 = readdir($dir2)){
					if (is_file(SABLOG_ROOT.$template_dir.'/'.$file1.'/'.$file2) && $file2 == 'info.txt'){
						$available_template_db[] = get_template_info($file1.'/'.$file2);
					}
				}
				closedir($dir2);
			}
		}
	}
	closedir($dir1);
	unset($file1);
	$subnav = '选择模板';
}

// 生成模板缓存
if($action == 'buildtemplate') {
	buildtemplate($path);
	redirect('更新模板缓存完毕');
}

//修改模板文件
if($action == 'mod' && $tpledit){
	$ext = in_array($ext,array('php','css')) ? $ext : 'php';
	$filepath = SABLOG_ROOT.$template_dir.$path.'/'.$file.'.'.$ext;
	if (file_exists($filepath)) {
		$writeable = false;
		if(is_writeable($filepath)) {
			$writeable = true;
		}
		$contents = htmlspecialchars(loadfile($filepath));
	} else {
		redirect('模板文件不存在', 'cp.php?job=template&action=filelist&path='.$path);
	}
	$subnav = '编辑模板';
}

//模板套系中的文件列表
if($action == 'filelist') {
	$desc = array(
		'archives' => '归档列表',
		'comments' => '评论列表',
		'footer' => '页面底部',
		'header' => '页面头部',
		'links' => '友情链接列表',
		'list' => '列表模式',
		'login' => '登陆',
		'message' => '消息提示',
		'sidecomm' => '侧栏公共模板',
		'normal' => '摘要模式',
		'profile' => '个人资料',
		'reg' => '注册',
		'search' => '搜索表单',
		'show' => '文章显示',
		'style' => '风格样式',
		'tag' => '标签列表',
		'trackbacks' => 'Trackback列表',
		'functions' => '自定义函数'
	);
	require_once(SABLOG_ROOT.'include/func/attachment.func.php');
	$dir = $template_dir.$path;
	$fp = opendir($dir);
	$i = 0;
	$filedb = array();
	while ($fileinfo = readdir($fp)) {
		if ($fileinfo != '.' && $fileinfo != '..' && $fileinfo != 'index.php' && is_file(SABLOG_ROOT.$dir.'/'.$fileinfo)) {
			$extension = getextension($fileinfo);
			if ($extension == 'php' || $extension == 'css') {
				$i++;
				$filedb[$i]['filename'] = str_replace(array('.php','.css'), '', $fileinfo);
				$filedb[$i]['filedesc'] = $desc[$filedb[$i]['filename']] ? $desc[$filedb[$i]['filename']] : $filedb[$i]['filename'];
				$filedb[$i]['extension'] = $extension;
			}
		}
	}
	closedir($fp);
	asort($filedb);
	unset($fileinfo);

	!$file && $file = 'show';
	$ext = in_array($ext,array('php','css')) ? $ext : 'php';
	$filepath = SABLOG_ROOT.$dir.'/'.$file.'.'.$ext;
	if (file_exists($filepath)) {
		$writeable = false;
		if(is_writeable($filepath)) {
			$writeable = true;
		}
		$contents = htmlspecialchars(loadfile($filepath));
	}
	$subnav = '编辑模板';
}

$navlink_L = ' &raquo; <a href="cp.php?job=template">模板管理</a>'.($subnav ? ' &raquo; '.$subnav : '');
cpheader($subnav);
include template('template');
?>